<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card class="box-card">
      <!-- 搜索区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUsersList">
            <el-button slot="append" icon="el-icon-search" @click="getUsersList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区 -->
      <el-table :data="usersList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <!-- 作用域插槽 -->
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="190">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editDialog(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUser(scope.row.id)"
            ></el-button>
            <!-- 分配按钮 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 点击添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="40%" @close="dialogClose">
      <!-- 内容 -->
      <span>
        <el-form :model="addFrom" :rules="addFromRules" class="addFrom" ref="addFromRef">
          <el-form-item label="用户名称" prop="username">
            <el-input v-model="addFrom.username"></el-input>
          </el-form-item>
          <el-form-item label="用户密码" prop="password">
            <el-input v-model="addFrom.password"></el-input>
          </el-form-item>
          <el-form-item label="用户邮箱" prop="email">
            <el-input v-model="addFrom.email"></el-input>
          </el-form-item>
          <el-form-item label="用户电话" prop="mobile">
            <el-input v-model="addFrom.mobile"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog title="修改用户" :visible.sync="showEditDialog" width="40%" @close="editDialogClose">
      <!-- 内容 -->
      <span>
        <el-form :model="editUser" :rules="addFromRules" ref="editFormRef" label-width="100px">
          <el-form-item label="用户名称" prop="username">
            <el-input v-model="editUser.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="用户邮箱" prop="email">
            <el-input v-model="editUser.email"></el-input>
          </el-form-item>
          <el-form-item label="用户电话" prop="mobile">
            <el-input v-model="editUser.mobile"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showEditDialog = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 角色分配对话框 -->
    <el-dialog title="角色分配" :visible.sync="showRole" width="40%" @close="roleClose" >
      <div>
        <p>当前的用户：{{userInfo.username}}</p>
        <p>当前的角色：{{userInfo.role_name}}</p>
        <p>分配新角色：
          <el-select v-model="selectRole" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id ">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showRole = false">取 消</el-button>
        <el-button type="primary" @click="svaeRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    //邮箱的校验规则
    var checkEmail = (rule, value, callback) => {
      //校验邮箱的正则
      const regEmail = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/;
      //判断
      if (regEmail.test(value)) {
        return callback();
      } else {
        return callback(new Error("请输入合法的邮箱"));
      }
    };
    //电话的校验规则
    var checkMobile = (rule, value, callback) => {
      //校验电话的正则
      const regMobile = /^[1][3,4,5,7,8][0-9]{9}$/;
      //判断
      if (regMobile.test(value)) {
        return callback();
      } else {
        return callback(new Error("请输入合法的手机号"));
      }
    };
    return {
      queryInfo: {
        query: "",
        //当前页数
        pagenum: 1,
        //当前页显示数据
        pagesize: 2
      },
      //获取用户列表数据
      usersList: [],
      total: 0,
      //控制添加用户对话框是否显示
      dialogVisible: false,
      //控制修改用户对话框是否显示
      showEditDialog: false,
      //添加用户数据绑定对象
      addFrom: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      //添加用户数据校验对象
      addFromRules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入用户密码", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入用户邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入用户电话", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      },
      //保存 通过id获取的参数
      editUser: {},
      //当前点击角色保存
      userInfo: [],
      //角色分配对话框是否显示
      showRole: false,
      //角色列表保存
      roleList: [],
      //下拉列表绑定数据
      selectRole: []
    };
  },
  created() {
    this.getUsersList();
  },
  methods: {
    //获取用户列表数据
    async getUsersList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo
      });

      if (res.meta.status !== 200) {
        this.$message.error("用户列表获取失败！");
      }

      this.usersList = res.data.users;
      this.total = res.data.total;
    },
    //监听pagesize改变事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getUsersList();
    },
    //监听页码值改变事件
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getUsersList();
    },
    //监听状态的改变
    async userStateChanged(userInfo) {
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      );

      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state;
        this.$message.error("更新用户状态失败！");
      }
      this.$message.success("更新用户状态成功！");
    },
    //监听添加用户关闭事件
    dialogClose() {
      //清楚from表单数据
      this.$refs.addFromRef.resetFields();
    },
    //点击按钮，添加用户事件
    addUser() {
      this.$refs.addFromRef.validate(async valid => {
        if (!valid) return;
        //发送请求
        const { data: res } = await this.$http.post("users", this.addFrom);
        console.log(res);
        if (res.meta.status == 201) {
          this.$message.success("添加用户成功！");
        } else {
          this.$message.error("添加用户失败！");
        }
        //添加后让 弹框消失
        this.dialogVisible = false;
        //然后重新请求数据
        this.getUsersList();
      });
    },
    //修改用户信息
    async editDialog(id) {
      const { data: res } = await this.$http.get("users/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error("请求失败！");
      }
      this.editUser = res.data;
      this.showEditDialog = true;
    },
    //监听修改对话框关闭重置
    editDialogClose() {
      this.$refs.editFormRef.resetFields();
    },
    //监听修改对话框提交操作
    editUserInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          "users/" + this.editUser.id,
          {
            email: this.editUser.email,
            mobile: this.editUser.mobile
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("修改失败！");
        }
        this.showEditDialog = false;
        this.getUsersList();
        this.$message.success("修改成功！");
      });
    },
    //删除用户事件
    removeUser(id) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const { data: res } = await this.$http.delete("users/" + id);
          if (res.meta.status !== 200) {
            return this.$message.error("删除失败！");
          }
          this.getUsersList();
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //角色分配展示信息
    async setRole(userInfo) {
      //将点击的用户信息保存data 用于展示
      this.userInfo = userInfo;
      const {data: res} = await this.$http.get('roles')

      if(res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      this.roleList = res.data
      this.showRole = true
    },
    //点击按钮 分配角色
    async svaeRoleInfo() {
      if(!this.selectRole) {
        return this.$message.error('请选择要分配的角色!')
      }
      const {data: res} = await this.$http.put(`users/${this.userInfo.id}/role`,{rid: this.selectRole})
      if(res.meta.status !== 200) {
        return this.$message.error('更新角色失败！')
      }
      this.$message.success('更新角色成功!')
      this.getUsersList()
      this.showRole = false
    },
    //监听分配角色关闭事件
    roleClose() {
      this.selectRole = ''
      this.userInfo = []
    }
  }
};
</script>

<style lang="less" scoped>
.el-table {
  margin-top: 20px;
  font-size: 12px;
}
.addFrom {
  .el-input {
    width: 70%;
    margin-left: 20px;
    height: 30px;
  }
}
</style>